package fr.alesia.deepstack.servlet;

import java.io.IOException;
import java.util.Set;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import fr.alesia.deepstack.bean.Player;
import fr.alesia.deepstack.data.PlayerDao;
import fr.alesia.deepstack.factory.BeanFactory;
import fr.alesia.deepstack.factory.DaoFactory;

@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet {

	private static final Logger logger = Logger.getLogger("deepstack");
	
	@Override
	protected void doGet(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		
		UserService service = UserServiceFactory.getUserService();
		User user = service.getCurrentUser();
		String name = request.getParameter("name");
		ServletContext context = this.getServletContext();
		
		if(name == null){
			
			RequestDispatcher dispatcher = context.getRequestDispatcher("/webapp/page/private/registration.jsp");
			dispatcher.forward(request, response);
		}
		else{
			
			if(name.trim().length() == 0){
				request.setAttribute("message", "Name must not be empty");
				RequestDispatcher dispatcher = context.getRequestDispatcher("/webapp/page/private/registration.jsp");
				dispatcher.forward(request, response);
			}
			
			else{
				
				PlayerDao playerDao =  DaoFactory.getPlayerDao();
				Set<Player> players = playerDao.findAll();
				boolean exists = false;
				for (Player player : players) {
					if(player.getName().equals(name)){
						exists = true;
						break;
					}
				}
				
				if(exists){
					request.setAttribute("message", "Player " + name + " already exists");
					RequestDispatcher dispatcher = context.getRequestDispatcher("/webapp/page/private/registration.jsp");
					dispatcher.forward(request, response);
					
				}
				else{
					Player player = BeanFactory.createPlayer(name, user);
					playerDao.insert(player);
					logger.info(player.toString());
					request.setAttribute("player", player);
					RequestDispatcher dispatcher = context.getRequestDispatcher("/webapp/page/private/registered.jsp");
					dispatcher.forward(request, response);
				}
			}
		}
	}

	@Override
	protected void doPost (
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		
		this.doGet(request, response);
	}
}
